package com.k.rabbitmq.amqp.demo;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

public class Test {
    private static final String EXCHANGE_NAME = "TEST_EXCHANGE_LOG";//""SMP_EXCHANGE_DATA_CHANGE";
    private static String getMessage() {
        return "haha";
    }

    private static String getRouting() {
//        return "DATA.CHANGE.DISTRICT";
        return "log.icc";
    }

    private static void send() throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("10.110.12.159");
        factory.setUsername("admin");
        factory.setPassword("Command_123");
        factory.setPort(27000);
        factory.setVirtualHost("mcc_vhost_dev");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {

            // 开启发送确认模式
            channel.confirmSelect();

            // EXCHANGE 已经存在不需要声明
//            channel.exchangeDeclare(EXCHANGE_NAME, "topic");

            String routingKey = getRouting();
            String message = getMessage();

            channel.basicPublish(EXCHANGE_NAME, routingKey, null, message.getBytes("UTF-8"));
            System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");


            // 消息发送确认返回值
            //boolean status = sendStatus(channel);
            channel.addConfirmListener(new ConfirmListener() {
                @Override
                public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                    System.out.println("已确认消息: deliveryTag:"+deliveryTag+" mutiple:"+multiple);
                }
                @Override
                public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                    System.out.println("未确认消息");
                }
            });
        }
    }

    private static boolean sendStatus(Channel channel) throws InterruptedException, IOException {
        // 方式一：普通Confirm模式
//        boolean status1 = channel.waitForConfirms();
//        System.out.println("status:"+status1);
//
//        // 方式二：批量Confirm模式
//        channel.waitForConfirmsOrDie();;

        // 方式三：异步Confirm模式
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("已确认消息");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("未确认消息");
            }
        });
        return true;
    }

    public static void main(String[] args) {
        try {
            send();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
